import { Image, Search, Sidebar, List, Loading, Navbar } from "@taroify/core";
import { View } from "@tarojs/components";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import StyleModule from "./index.module.scss";
import { ArrowDown, Play, ShoppingCartOutlined } from "@taroify/icons";
import Taro, { useDidShow, useReady } from "@tarojs/taro";
import { requestPOST } from "@/request";
import useSyncCallback from "@/hooks/useSyncCallback";
import { useSelector } from "react-redux";
import { RootState } from "@/store";

export default function Product() {
  const accountType = useSelector(
    (state: RootState) => state.userInfo.accountType
  );
  const merchantInfo = useSelector(
    (state: RootState) => state.userInfo.merchantInfo
  );

  const baseURL = process.env.TARO_APP_API;

  const [productTypes, setProductTypes] = useState<any>([]);
  const productTypeId = useRef(null);
  const [loading, setLoading] = useState(false);

  const [productNames, setProductNames] = useState<any>([]);
  const [showProductName, setShowProductNames] = useState(
    productNames.slice(0, 5)
  );
  const [selectName, setSelectName] = useState("");

  const [ruleNames, setRuleNames] = useState<any>([]);
  const [selectRuleName, setSelectRuleName] = useState("");

  const [keyword, setKeyword] = useState("");
  const [height, setHeight] = useState(0);
  const query = Taro.createSelectorQuery();
  const [priceOrder, setPriceOrder] = useState("");
  const [salesOrder, setSalesOrder] = useState("");
  const [synthesize, setSynthesize] = useState(false);

  const [productList, setProductList] = useState<any[]>([]);
  const [loading1, setLoading1] = useState(false);
  const pageNum = useRef(1);
  const total = useRef(0);
  const [hasMore, setHasMore] = useState(true);

  const onLoad = () => {
    console.log("onload");
    pageNum.current++;
    if (pageNum.current === 1) return;
    getProducltDataList();
  };

  const getProducltDataList = useSyncCallback(() => {
    console.log("selectName", selectName);
    if (!selectName || !selectRuleName) {
      setHasMore(false);
      return;
    }
    setLoading1(true);
    requestPOST("product/getProductListByParam", {
      isPage: 1,
      pageNumIndex: pageNum.current,
      pageSizeIndex: 10,
      typeId: productTypeId.current,
      typeBrand: selectName,
      typeSpecifications: selectRuleName,
      searchName: keyword,
      comprehensiveSort: Number(synthesize),
      priceSort: priceOrder === "asc" ? 0 : priceOrder === "desc" ? 1 : "",
      saleSort: salesOrder === "asc" ? 0 : salesOrder === "desc" ? 1 : "",
    })
      .then((res: any) => {
        const { vos } = res;
        total.current = res.total;
        const result = [...productList, ...vos];
        setProductList([...result]);
        if (total.current <= result.length) {
          setHasMore(false);
        }
      })
      .finally(() => {
        setLoading1(false);
      });
  });

  const getProductTypes = () => {
    setLoading(true);
    requestPOST("product/getProductTypeList", {
      params: {
        searchProductList: false,
        productListParams: {
          isPage: false,
        },
      },
    })
      .then((res: any) => {
        setProductTypes([...res]);
        productTypeId.current = res[0].id;
        setProductNames(
          Array.isArray(res[0].typeBrand) ? [...res[0].typeBrand] : []
        );
        setShowProductNames(
          Array.isArray(res[0].typeBrand)
            ? [...res[0].typeBrand].slice(0, 5)
            : []
        );
        setRuleNames(
          Array.isArray(res[0].typeSpecifications)
            ? [...res[0].typeSpecifications]
            : []
        );
        setSelectName(res[0]?.typeBrand?.[0]);
        setSelectRuleName(res[0]?.typeSpecifications?.[0]);
        getProducltDataList();
      })
      .finally(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    getProductTypes();
    getBoxHeight();
  }, []);

  // 动态获取高度
  const getBoxHeight = () => {
    let height = 0;
    let height1 = 0;
    query
      .select(".taroContainer")
      .boundingClientRect((res: any) => {
        height = res?.height || 0;
        console.log("123123");
      })
      .exec();
    query
      .select(".box")
      .boundingClientRect((res1: any) => {
        height1 = res1?.height || 0;
        console.log("123123");
      })
      .exec();

    setTimeout(() => {
      console.log(height, height1);
      setHeight(height - height1 - 90);
    }, 500);
  };

  const showMore = () => {
    if (showProductName.length === productNames.length) {
      setShowProductNames(productNames.slice(0, 5));
    } else {
      setShowProductNames([...productNames]);
    }
    getBoxHeight();
  };
  // 选择品牌
  const selectProductName = (name) => {
    setSelectName(name);
    initProductDataList();
    getProducltDataList();
  };

  // 选择规格
  const selectHandleRuleName = (name) => {
    setSelectRuleName(name);
    initProductDataList();
    getProducltDataList();
  };

  const setSynthesizeFun = () => {
    setSynthesize(!synthesize);
    initProductDataList();
    getProducltDataList();
  };

  const setPriceOrderFun = () => {
    if (priceOrder === "") {
      setPriceOrder("asc");
    } else if (priceOrder === "asc") {
      setPriceOrder("desc");
    } else {
      setPriceOrder("");
    }
    initProductDataList();
    getProducltDataList();
  };

  const setSalesOrderFun = () => {
    if (salesOrder === "") {
      setSalesOrder("asc");
    } else if (salesOrder === "asc") {
      setSalesOrder("desc");
    } else {
      setSalesOrder("");
    }
    initProductDataList();
    getProducltDataList();
  };

  const handleSidebarChange = (index) => {
    initProductDataList();

    const id = productTypes[index].id;
    productTypeId.current = id;
    setProductNames(
      Array.isArray(productTypes[index].typeBrand)
        ? [...productTypes[index].typeBrand]
        : []
    );
    setShowProductNames(
      Array.isArray(productTypes[index].typeBrand)
        ? [...productTypes[index].typeBrand].slice(0, 5)
        : []
    );
    setRuleNames(
      Array.isArray(productTypes[index].typeSpecifications)
        ? [...productTypes[index].typeSpecifications]
        : []
    );
    setSelectName(productTypes[index]?.typeBrand?.[0]);
    setSelectRuleName(productTypes[index]?.typeSpecifications?.[0]);
    getProducltDataList();
    getBoxHeight();
  };

  const initProductDataList = () => {
    setHasMore(true);
    setProductList([]);
    pageNum.current = 1;
  };

  const handleSearch = () => {
    initProductDataList();
    getProducltDataList();
  };

  return (
    <View
      className="taroContainer"
      style={{ display: "flex", flexDirection: "column", overflow: "hidden" }}
    >
      <Navbar
        fixed
        nativeSafeTop
        safeArea="top"
        className="navBar"
        style={{ background: "#e3f3fe" }}
        placeholder={true}
      >
        <Navbar.Title style={{ maxWidth: "100%" }}>
          <View
            style={{
              display: "flex",
              alignItems: "center",
              width: "100vw",
              justifyContent: "center",
              position: "relative",
              fontSize: "28rpx",
              fontWeight: "normal",
            }}
          >
            <View style={{ position: "absolute", left: 20 }}>
              {merchantInfo.merchantName}
            </View>
            <View>选品</View>
          </View>
        </Navbar.Title>
      </Navbar>
      <View
        style={{
          flex: 1,
          display: "flex",
          background: "#fff",
          overflow: "hidden",
        }}
      >
        <View
          style={{
            width: "174rpx",
            background: "#f3fafe",
            height: "100%",
            display: "flex",
            flexDirection: "column",
          }}
        >
          <View
            style={{
              fontWeight: "bold",
              fontSize: "33rpx",
              color: "#333333",
              padding: "22rpx 0",
              textAlign: "center",
            }}
          >
            品类
          </View>
          <View style={{ overflowY: "auto", flex: "1" }}>
            {loading && (
              <View style={{ textAlign: "center" }}>
                <Loading style={{ color: "#1989fa" }} />
              </View>
            )}
            <Sidebar onChange={handleSidebarChange}>
              {productTypes.map((item) => (
                <Sidebar.Tab key={item.id}>{item.typeName}</Sidebar.Tab>
              ))}
            </Sidebar>
          </View>
        </View>
        <View
          style={{
            fontSize: "25rpx",
            flex: 1,
            display: "flex",
            flexDirection: "column",
            height: "100%",
            overflow: "hidden",
            boxSizing: "border-box",
          }}
        >
          <View className="box" style={{ padding: "32rpx" }}>
            <View style={{ display: "flex" }}>
              <View>品牌：</View>
              <View
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(3,1fr)",
                  flex: 1,
                  gap: "20rpx 30rpx",
                }}
              >
                {loading ? (
                  <View style={{ textAlign: "center" }}>
                    <Loading style={{ color: "#1989fa" }} size={12} />
                  </View>
                ) : (
                  <>
                    {showProductName.map((item) => (
                      <View
                        key={item}
                        style={{ textAlign: "center" }}
                        className={
                          item === selectName ? StyleModule.active : ""
                        }
                        onClick={() => selectProductName(item)}
                      >
                        {item}
                      </View>
                    ))}
                    {productNames.length > 5 && (
                      <View style={{ color: "#00A2FF" }} onClick={showMore}>
                        全部品牌
                        <ArrowDown
                          style={{
                            transform:
                              productNames.length === showProductName.length
                                ? "rotate(180deg)"
                                : "rotate(0deg)",
                            transition: ".3s all",
                          }}
                        />
                      </View>
                    )}
                  </>
                )}
              </View>
            </View>
            <View style={{ display: "flex", marginTop: "40rpx" }}>
              <View>规格：</View>
              <View
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(3,1fr)",
                  flex: 1,
                  textAlign: "center",
                  gap: "20rpx 30rpx",
                }}
              >
                {loading ? (
                  <View style={{ textAlign: "center" }}>
                    <Loading style={{ color: "#1989fa" }} size={12} />
                  </View>
                ) : (
                  ruleNames.map((item) => (
                    <View
                      key={item}
                      className={`${
                        item === selectRuleName ? StyleModule.active1 : ""
                      } ${StyleModule.item}`}
                      onClick={() => selectHandleRuleName(item)}
                    >
                      {item}
                    </View>
                  ))
                )}
              </View>
            </View>
            <View style={{ marginTop: "40rpx" }}>
              <View
                style={{ display: "flex", alignItems: "center", gap: "20rpx" }}
              >
                <Search
                  style={{ flex: 1, padding: "0rpx" }}
                  value={keyword}
                  placeholder="请输入"
                  onChange={(e) => setKeyword(e.detail.value)}
                  onSearch={handleSearch}
                />
                <View
                  onClick={setSynthesizeFun}
                  style={{ color: synthesize ? "#00a2ff" : "" }}
                >
                  综合
                </View>
                <View
                  style={{ display: "flex", alignItems: "center", gap: "5rpx" }}
                  onClick={setPriceOrderFun}
                >
                  <View>价格</View>
                  <View
                    style={{
                      display: "flex",
                      flexDirection: "column",
                    }}
                  >
                    <Play
                      style={{
                        transform:
                          "rotate(-90deg) translateX(-6rpx) translateY(0rpx)",
                      }}
                      color={priceOrder === "asc" ? "#00a2ff" : ""}
                    />
                    <Play
                      style={{ transform: "rotate(90deg) translateX(-6rpx)" }}
                      color={priceOrder === "desc" ? "#00a2ff" : ""}
                    />
                  </View>
                </View>
                <View
                  style={{ display: "flex", alignItems: "center", gap: "5rpx" }}
                  onClick={setSalesOrderFun}
                >
                  <View>销量</View>
                  <View
                    style={{
                      display: "flex",
                      flexDirection: "column",
                    }}
                  >
                    <Play
                      style={{
                        transform:
                          "rotate(-90deg) translateX(-6rpx) translateY(0rpx)",
                      }}
                      color={salesOrder === "asc" ? "#00a2ff" : ""}
                    />
                    <Play
                      style={{ transform: "rotate(90deg) translateX(-6rpx)" }}
                      color={salesOrder === "desc" ? "#00a2ff" : ""}
                    />
                  </View>
                </View>
              </View>
            </View>
          </View>

          <View
            style={{
              flex: 1,
              padding: "0 0 0 32rpx",
              boxSizing: "border-box",
            }}
          >
            <List
              fixedHeight
              style={{ height: height }}
              loading={loading1}
              hasMore={hasMore}
              onLoad={onLoad}
            >
              <View
                style={{
                  display: "flex",
                  flexDirection: "column",
                  gap: "20rpx",
                }}
              >
                {productList.map((item) => (
                  <View
                    key={item.id}
                    style={{
                      position: "relative",
                      overflow: "hidden",
                      display: "flex",
                      backgroundColor: "#fff",
                      alignItems: "center",
                      borderBottom: "1px solid #efefef",
                      paddingBottom: "40rpx",
                    }}
                    onClick={(e) => {
                      e.stopPropagation();
                      Taro.navigateTo({
                        url: `/packages/goodsDetail/index?id=${item.id}`,
                      });
                    }}
                  >
                    <View style={{ flex: "0 0 180rpx" }}>
                      <Image
                        src={baseURL + item.productImage[0]}
                        width={180}
                        height={180}
                        mode="aspectFill"
                        style={{ borderRadius: "14rpx" }}
                      />
                    </View>

                    <View
                      style={{
                        padding: "0 26rpx 0 26rpx",
                        display: "flex",
                        flexDirection: "column",
                      }}
                    >
                      <View
                        style={{
                          gap: "20rpx",
                        }}
                      >
                        <View
                          style={{
                            background: "#FF4444",
                            borderRadius: "7rpx",
                            color: "#FFFEFE",
                            fontSize: "22rpx",
                            height: "33rpx",
                            lineHeight: "33rpx",
                            width: "64rpx",
                            textAlign: "center",
                            display: "inline-block",
                            marginRight: "10rpx",
                          }}
                        >
                          推荐
                        </View>
                        <View
                          style={{
                            fontSize: "25rpx",
                            color: "#333",
                            display: "inline",
                          }}
                        >
                          {item.productName}
                        </View>
                      </View>
                      <View style={{ fontSize: "21rpx", color: "#999" }}>
                        {item.productTag.join(" | ")}
                      </View>
                      <View
                        style={{
                          display: "flex",
                          alignItems: "baseline",
                          marginTop: "20rpx",
                        }}
                      >
                        <View
                          style={{
                            fontWeight: "bold",
                            fontSize: "21rpx",
                            color: "#f90000",
                          }}
                        >
                          ￥
                        </View>
                        <View
                          style={{
                            fontWeight: "bold",
                            fontSize: "33rpx",
                            color: "#f90000",
                          }}
                        >
                          {item.currentPrice}
                        </View>
                        <View
                          style={{
                            fontSize: "21rpx",
                            color: "#AAAAAA",
                            textDecorationLine: "line-through",
                            marginLeft: "15rpx",
                          }}
                        >
                          ￥{item.originalPrice}
                        </View>
                      </View>
                      <View style={{ fontSize: "21rpx", color: "#999999" }}>
                        已售{item.salesVolume || 0}
                      </View>
                      <View
                        style={{
                          position: "absolute",
                          right: "30rpx",
                          bottom: "30rpx",
                          width: "56rpx",
                          height: "56rpx",
                          background: "linear-gradient( #52b4f9, #3a84f7)",
                          borderRadius: "50%",
                          display: "grid",
                          placeContent: "center",
                        }}
                        onClick={(e) => {
                          e.stopPropagation();
                          console.log("12123");
                        }}
                      >
                        <ShoppingCartOutlined size={17} color="#fff" />
                      </View>
                    </View>
                  </View>
                ))}
              </View>
              <List.Placeholder>
                {(loading1 || loading) && <Loading>加载中...</Loading>}
                {!hasMore && !loading && "没有更多了"}
              </List.Placeholder>
            </List>
          </View>
        </View>
      </View>
    </View>
  );
}
